; (function () {
    let position = 'absolute'
    // 记录创建的蛇
    let snakes = []
    function Snake(options) {
        // 蛇节的大小
        options = options || {}
        this.width = options.width || 20
        this.height = options.height || 20

        // 蛇移动的方向
        this.direction = options.diretion || 'right'

        // 蛇的身体, 第一元素是蛇头部
        this.body = [
            { x: 3, y: 2, color: 'red' },
            { x: 2, y: 2, color: 'pink' },
            { x: 1, y: 2, color: 'hotpink' }
        ]
    }

    // 渲染蛇
    Snake.prototype.render = function (map) {
        // 删除之前创建的蛇
        remove()

        for (let i = 0, len = this.body.length; i < len; i++) {
            // 蛇节的身体属性
            let smallSnake = this.body[i]

            // 创建蛇节
            let snakeBox = document.createElement('div')

            // 添加蛇样式
            snakeBox.style.position = position
            snakeBox.style.top = smallSnake.y * this.width + 'px'
            snakeBox.style.left = smallSnake.x * this.height + 'px'
            snakeBox.style.width = this.width + 'px'
            snakeBox.style.height = this.height + 'px'
            snakeBox.style.backgroundColor = smallSnake.color

            map.appendChild(snakeBox)
            snakes.push(snakeBox)
        }
    }

    // 删除蛇节
    function remove() {
        for (let i = snakes.length - 1; i >= 0; i--) {
            // 删除蛇节
            snakes[i].parentNode.removeChild(snakes[i])
            // 删除数组中的元素
            snakes.length--
        }
    }

    // 控制蛇移动的方向和增加蛇节数
    Snake.prototype.move = function (food, map) {
        // 控制蛇的身体移动 (当前蛇节 到 上一个蛇节的位置)
        for (let i = this.body.length - 1; i > 0; i--) {
            this.body[i].x = this.body[i - 1].x
            this.body[i].y = this.body[i - 1].y
        }
        // 控制蛇头的移动
        // 判断蛇头移动的方向
        let snakeHead = this.body[0]
        switch (this.direction) {
            case 'right':
                snakeHead.x++
                break
            case 'left':
                snakeHead.x--
                break
            case 'top':
                snakeHead.y--
                break
            case 'bottom':
                snakeHead.y++
                break
        }
        // 蛇吃食物 (判断蛇头是否和食物的坐标重合)
        let headX = snakeHead.x * this.width
        let headY = snakeHead.y * this.height
        if (food.x === headX && food.y === headY) {
            // 让蛇增加一节
            let last = this.body[this.body.length - 1]
            this.body.push({
                x: last.x,
                y: last.y,
                color: last.color
            })
            // 随机生成食物
            food.render(map)
        }
    }
    window.Snake = Snake
})()
